package com.lzy.ninegrid.preview;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.view.PagerAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.flyco.dialog.listener.OnOperItemClickL;
import com.flyco.dialog.widget.ActionSheetDialog;
import com.lzy.ninegrid.ImageInfo;
import com.lzy.ninegrid.NineGridView;
import com.lzy.ninegrid.R;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

import uk.co.senab.photoview.PhotoView;
import uk.co.senab.photoview.PhotoViewAttacher;

/**
 * ================================================
 * 作    者：廖子尧
 * 版    本：1.0
 * 创建日期：2016/3/21
 * 描    述：
 * 修订历史：
 * ================================================
 */
public class ImagePreviewAdapter extends PagerAdapter implements PhotoViewAttacher.OnPhotoTapListener {

    private List<ImageInfo> imageInfo;
    private Context context;
    private View currentView;
    private ProgressBar pb;
//    private PhotoView imageView;

    public ImagePreviewAdapter(Context context, @NonNull List<ImageInfo> imageInfo) {
        super();
        this.imageInfo = imageInfo;
        this.context = context;
    }

    @Override
    public int getCount() {
        return imageInfo.size();
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return view == object;
    }

    @Override
    public void setPrimaryItem(ViewGroup container, int position, Object object) {
        super.setPrimaryItem(container, position, object);
        currentView = (View) object;
    }

    public View getPrimaryItem() {
        return currentView;
    }

    public ImageView getPrimaryImageView() {
        return (ImageView) currentView.findViewById(R.id.pv);
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        View view = LayoutInflater.from(context).inflate(R.layout.item_photoview, container, false);
        pb = (ProgressBar) view.findViewById(R.id.pb);
        final PhotoView imageView = (PhotoView) view.findViewById(R.id.pv);

        ImageInfo info = this.imageInfo.get(position);
        imageView.setOnPhotoTapListener(this);
        /*臧学强2016-08-31 增加长按事件进行图片数据保存*/
        imageView.setOnLongClickListener(new View.OnLongClickListener() {

            private String[] stringItems;
            private ActionSheetDialog dialog;

            @Override
            public boolean onLongClick(View v) {

                stringItems = new String[]{"保存到本地"};
                dialog = new ActionSheetDialog(context, stringItems, null);
                dialog.isTitleShow(false).show();
                dialog.setOnOperItemClickL(new OnOperItemClickL() {
                    @Override
                    public void onOperItemClick(AdapterView<?> parent, View view, int position, long id) {
                        switch (position) {
                            case 0:
                                // 首先保存图片
                                //臧学强20161128重新获取图片
                                imageView.buildDrawingCache(true);
                                final Bitmap bmp = imageView.getDrawingCache(true).copy(Bitmap.Config.RGB_565, false);
                                imageView.destroyDrawingCache();
                                File appDir = new File(Environment.getExternalStorageDirectory(), "智慧校园");
                                if (!appDir.exists()) {
                                    appDir.mkdir();
                                }
                                String fileName = System.currentTimeMillis() + ".jpg";
                                File file = new File(appDir, fileName);
                                try {
                                    FileOutputStream fos = new FileOutputStream(file);
                                    bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
                                    fos.flush();
                                    fos.close();
                                } catch (FileNotFoundException e) {
                                    Toast.makeText(context, "保存失败", Toast.LENGTH_SHORT).show();
                                    e.printStackTrace();
                                    return;
                                } catch (IOException e) {
                                    Toast.makeText(context, "保存失败", Toast.LENGTH_SHORT).show();
                                    e.printStackTrace();
                                    return;
                                }

                                // 其次把文件插入到系统图库
                                try {
                                    MediaStore.Images.Media.insertImage(context.getContentResolver(),
                                            file.getAbsolutePath(), fileName, null);
                                } catch (FileNotFoundException e) {
                                    Toast.makeText(context, "保存失败", Toast.LENGTH_SHORT).show();
                                    e.printStackTrace();
                                    return;
                                }
                                // 最后通知图库更新
                                context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + file.getAbsolutePath())));
                                if (!bmp.isRecycled()) {
                                    bmp.recycle();
                                    System.gc();
                                }
                                Toast.makeText(context, "保存成功", Toast.LENGTH_SHORT).show();
                                /*String root = Environment.getExternalStorageDirectory().getPath();
                                String fileName = TimeUtils.milliseconds2String(System.currentTimeMillis(), new SimpleDateFormat("yyyyMMddHHmmss", Locale.getDefault())) + ".png";
                                String filePath = root + File.separator + "xsms" + File.separator + fileName;
                                File file = new File(filePath);
                                boolean ret = false;
                                if (!file.exists()) {
                                    try {
                                        ret = file.createNewFile();
                                    } catch (Exception e) {
                                        String s = e.getMessage();
                                    }
                                }

                                if (FileUtils.createOrExistsFile(filePath)) {
                                    imageView.buildDrawingCache(true);
                                    Bitmap bitmap = imageView.getDrawingCache(true).copy(Bitmap.Config.RGB_565, false);
                                    imageView.destroyDrawingCache();
                                    try {
                                        BufferedOutputStream bos = new BufferedOutputStream(
                                                new FileOutputStream(filePath));
                                        try {
                                            bitmap.compress(Bitmap.CompressFormat.JPEG, 85, bos);  // see here
                                        } catch (Exception e) {
                                            String s = e.getMessage();
                                        }
                                        bos.flush();
                                        bos.close();
                                        Toast.makeText(context,"保存成功", Toast.LENGTH_SHORT).show();
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }
                                }*/
                                break;
                            case 1:
                                break;
                        }
                        dialog.dismiss();
                    }
                });
               /* new SuperDialog.Builder((FragmentActivity) context)
                        //.setAlpha(0.5f)
                        //.setGravity(Gravity.CENTER)
                        //.setTitle("上传头像", ColorRes.negativeButton)
                        .setCanceledOnTouchOutside(false)
                        .setItems(list, new SuperDialog.OnItemClickListener() {
                            @Override
                            public void onItemClick(int position) {
                                switch (position) {
                                    case 0:
                                        String root = Environment.getExternalStorageDirectory().getPath();
                                        String fileName = TimeUtils.milliseconds2String(System.currentTimeMillis(), new SimpleDateFormat("yyyyMMddHHmmss", Locale.getDefault())) + ".png";
                                        String filePath = root + File.separator + "香山美墅" + File.separator + fileName;
                                        if (FileUtils.createOrExistsFile(filePath)) {
                                            imageView.buildDrawingCache(true);
                                            Bitmap bitmap = imageView.getDrawingCache(true).copy(Bitmap.Config.RGB_565, false);
                                            imageView.destroyDrawingCache();
                                            try {
                                                BufferedOutputStream bos = new BufferedOutputStream(
                                                        new FileOutputStream(filePath));
                                                try {
                                                    bitmap.compress(Bitmap.CompressFormat.JPEG, 85, bos);  // see here
                                                } catch (Exception e) {
                                                    String s = e.getMessage();
                                                }
                                                bos.flush();
                                                bos.close();
                                            } catch (Exception e) {
                                                e.printStackTrace();
                                            }
                                        }

                                        break;
                                    case 1:
                                        break;
                                }
                            }
                        })
                        .setNegativeButton("取消", null)
                        .build();*/

               /* StytledDialog.showBottomItemDialog(context, list, "cancle", true, true, new MyItemDialogListener() {
                    @Override
                    public void onItemClick(String text, int position) {
                        switch (position){
                            case 0:
                                String root = Environment.getExternalStorageDirectory().getPath();
                                String fileName= TimeUtils.milliseconds2String(System.currentTimeMillis(),new SimpleDateFormat("yyyyMMddHHmmss", Locale.getDefault()))+".png";
                                String filePath = root + File.separator + "香山美墅" + File.separator + fileName;
                                if(FileUtils.createOrExistsFile(filePath)) {
                                    imageView.buildDrawingCache(true);
                                    Bitmap bitmap = imageView.getDrawingCache(true).copy(Bitmap.Config.RGB_565, false);
                                    imageView.destroyDrawingCache();
                                    try {
                                        BufferedOutputStream bos = new BufferedOutputStream(
                                                new FileOutputStream(filePath));
                                        try {
                                            bitmap.compress(Bitmap.CompressFormat.JPEG, 85, bos);  // see here
                                        } catch (Exception e) {
                                            String s = e.getMessage();
                                        }
                                        bos.flush();
                                        bos.close();
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }
                                }

                                break;
                            case 1:
                                break;
                        }
                    }

                    @Override
                    public void onBottomBtnClick() {
//                        showToast("onItemClick");
                    }
                });*/
                return false;
            }
        });
        showExcessPic(info, imageView);

        //如果需要加载的loading,需要自己改写,不能使用这个方法
        NineGridView.getImageLoader().onDisplayImage(view.getContext(), imageView, info.bigImageUrl, info.key, 2);

//        pb.setVisibility(View.VISIBLE);
//        Glide.with(context).load(info.bigImageUrl)//
//                .placeholder(R.drawable.ic_default_image)//
//                .error(R.drawable.ic_default_image)//
//                .diskCacheStrategy(DiskCacheStrategy.ALL)//
//                .listener(new RequestListener<String, GlideDrawable>() {
//                    @Override
//                    public boolean onException(Exception e, String model, Target<GlideDrawable> target, boolean isFirstResource) {
//                        pb.setVisibility(View.GONE);
//                        return false;
//                    }
//
//                    @Override
//                    public boolean onResourceReady(GlideDrawable resource, String model, Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) {
//                        pb.setVisibility(View.GONE);
//                        return false;
//                    }
//                }).into(imageView);

        container.addView(view);
        return view;
    }

    /**
     * 展示过度图片
     */
    private void showExcessPic(ImageInfo imageInfo, PhotoView imageView) {
        //先获取大图的缓存图片
        Bitmap cacheImage = NineGridView.getImageLoader().getCacheImage(imageInfo.bigImageUrl);
        //如果大图的缓存不存在,在获取小图的缓存
        if (cacheImage == null)
            cacheImage = NineGridView.getImageLoader().getCacheImage(imageInfo.thumbnailUrl);
        //如果没有任何缓存,使用默认图片,否者使用缓存
        if (cacheImage == null) {
            imageView.setImageResource(R.drawable.ic_default_image);
        } else {
            imageView.setImageBitmap(cacheImage);
        }
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        container.removeView((View) object);
    }

    /**
     * 单击屏幕关闭
     */
    @Override
    public void onPhotoTap(View view, float x, float y) {
        ((ImagePreviewActivity) context).finishActivityAnim();
    }
}